package controllers;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import models.BeanUser;
import utils.BeanUtilities;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class logincontroller
 */
public class logincontroller extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public logincontroller() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		BeanUser user = new BeanUser();
		BeanUtilities.populateBean(user, request);
		ResultSet  login = null;
		System.out.println("ENTRA logincontroller-->" + user.getAlias() + ".");
	    try {
	    	DAO dao = new DAO();
			login = dao.loginUsuario(user.getAlias(), user.getPass());
			if (login.next()) {
				//ResultSet rs = dao.recuperaUsuario(user.getAlias());
		    	//HttpSession session = request.getSession();
		    	//session.setAttribute("user", user);
		    	RequestDispatcher dispatcher = request.getRequestDispatcher("registration_1.jsp");
		    	if (dispatcher != null) dispatcher.forward(request, response);
		    } else {
		    	int[] error = user.getError();
		    	error[0] = 1;
		    	request.setAttribute("user",user);
		    	RequestDispatcher dispatcher = request.getRequestDispatcher("login.jsp");
		    	if (dispatcher != null) dispatcher.forward(request, response);
		    }
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}

}
